package com.kandroid.sample5_1;

import android.content.Context;
import android.opengl.GLES30;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * Created by Kandroid on 06/09/2017.
 */

public class MySurfaceView extends GLSurfaceView {
    private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
    private SceneRenderer mRenderer;
    private float mPreviousY;
    private float mPreviousX;

    public MySurfaceView(Context context) {
        super(context);
        setEGLContextClientVersion(3);
        mRenderer = new SceneRenderer();
        setRenderer(mRenderer);
        setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        float y = e.getY();//获取此次触控的Y坐标
        float x = e.getX();//获取此次触控的X坐标
        switch (e.getAction()) {
            case MotionEvent.ACTION_MOVE://若为移动动作
                float dy = y - mPreviousY;
                float dx = x - mPreviousX;//计算触控位置的x,y位移
                for (SixPointedStar h : mRenderer.stars)//设置各个六角星绕x,y旋转的角度
                {
                    h.yAngle += dx * TOUCH_SCALE_FACTOR;
                    h.xAngle += dy * TOUCH_SCALE_FACTOR;
                }
        }
        mPreviousY = y;
        mPreviousX = x;
        return true;
    }

    private class SceneRenderer implements GLSurfaceView.Renderer {
        SixPointedStar[] stars = new SixPointedStar[6];

        public void onDrawFrame(GL10 gl) {
            GLES30.glClear(GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);
            for (SixPointedStar star : stars) {
                star.drawSelf();
            }
        }

        public void onSurfaceChanged(GL10 gl, int width, int height) {
            GLES30.glViewport(0, 0, width, height);
            float ratio = (float) width / height;
            MatrixState.setProjectOrtho(-ratio, ratio, -1, 1, 1, 10);

            MatrixState.setCamera(
                    0, 0, 3f,
                    0, 0, 0f,
                    0f, 1.0f, 0.0f
            );
        }

        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
            GLES30.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
            for (int i = 0; i < stars.length; i++) {
                stars[i] = new SixPointedStar(MySurfaceView.this, 0.15f, 0.5f, -0.2f * i);
            }
            GLES30.glEnable(GLES30.GL_DEPTH_TEST);
        }
    }
}
